<!DOCTYPE html>
<html>
  <head>
	<script src="settings.js" ></script>
    <script>
var regex = /https?:\/\/([^/]+)\/.?/i;
function onClick(tab) {
	var host = null;
	var match = tab.url.match(regex);
	if(match) {
		host = match[1];
	}
	for(var i=ports[host].length - 1; i>=0; i--) {
		try {
			port = ports[host][i];
			port.data.enabled = port.data.enabled? false : true;
			port.data.isDefault = undefined;
			port.setIcon();
			localStorage[host] = JSON.stringify(port.data);
			port.postMessage(port.data);
		} catch(exception) { }
	}
}
chrome.pageAction.onClicked.addListener(onClick);

var ports = {};
function sendPortData(port,i,a) {
	try {
		port.data = settings;
		port.setIcon();
		port.postMessage(port.data);
	} catch(exception) {}
}
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
	if(request.updateDomain) {
		var updateDomain = request.updateDomain;
		if(ports[updateDomain]) {
			settings = JSON.parse(localStorage[updateDomain]);
			ports[updateDomain].forEach(sendPortData);
		} else if(updateDomain == 'default') {
		// Have it go through all the ports on all the domains, and send them all messages for their settings
			for(key in ports) {
				// TODO: only do the forEach if this is a domain that uses the default settings.
				settings = getSettings(key);
				ports[key].forEach(sendPortData);
			}
		}
	}
	sendResponse({});
});
function getSettings(host) {
	var data;
	try {
		data = JSON.parse(localStorage[host]);
		if(data.version != CURRENT_SETTINGS_VERSION) {
			data = getDefaultData();
		}
	} catch(exception) {
		data = getDefaultData();
	}
	return data;
}
chrome.extension.onConnect.addListener(function(port) {
	var firstMessage = true;
	var host = null;
	var tabId = null;
	if(port.sender.tab) {
		tabId = port.sender.tab.id;
		match = port.sender.tab.url.match(regex);
		if(match) {
			host = match[1];
			if(ports[host]) {
				ports[host].push(port);
			} else {
				ports[host] = [port];
			}
		}
	}
	port.data = getSettings(host);
	
	port.setIcon = function() {
		chrome.pageAction.setIcon(
			{
				tabId: tabId,
				path: port.data.enabled? "pageAction.png" : "dpageAction.png"
			}
		);
	}
	port.setIcon();
	
	function onMessage(msg) {
		// Show the page action for the tab that the sender (content script)
		// was on.
		if(msg.show) {
			chrome.pageAction.show(tabId);
		} else {
			chrome.pageAction.hide(tabId);
		}
		if(msg.needReply) {
			port.postMessage(port.data);
		}
	}
	function onDisconnect() {
		// remove this port from ports[host]
		var index = ports[host].indexOf(port);
		while(index >= 0) {			
			ports[host].splice(index,1);
			index = ports[host].indexOf(port);
		}
	}
	port.onMessage.addListener(onMessage);
	port.onDisconnect.addListener(onDisconnect);
});
    </script>
  </head>
</html>
